unit uGxtSms;

interface

uses
  SysUtils, Classes, uDZSysUtils, uDZWinInetUtils, uDZHttp, uGxtTypes;

type
  TGxtSmsService = class
  private
    fHttpClient: TDzWinInetHttp;
    fSmsServiceUrl: AnsiString;
  public
    constructor Create;
    destructor Destroy; override;
    function SendSms(const UserID, Phone: AnsiString; const Msg: WideString;
      out ErrCode: Integer; out ErrMsg: WideString): Boolean;
    property SmsServiceUrl: AnsiString read fSmsServiceUrl write fSmsServiceUrl;
  end;

function SendSms(const Url, UserID, Phone: AnsiString; const Msg: WideString;
  out ErrCode: Integer; out ErrMsg: WideString): Boolean;

implementation

uses
  DLMD5, uDZXML, uGWCommonLog;

function SMSMD5(const data: AnsiString): AnsiString;
begin
  Result := MD5Hex('DLPW'#9#0 + data + #13#10#26);
end;
  
function SendSms(const Url, UserID, Phone: AnsiString; const Msg: WideString;
  out ErrCode: Integer; out ErrMsg: WideString): Boolean;
var
  SmsSvc: TGxtSmsService;
begin
  SmsSvc := TGxtSmsService.Create;
  try
    SmsSvc.SmsServiceUrl := Url;
    Result := SmsSvc.SendSms(UserID, Phone, Msg, ErrCode, ErrMsg);
  finally
    SmsSvc.Free;
  end;
end;

{ TGxtSmsService }

constructor TGxtSmsService.Create;
begin
  fHttpClient := TDzWinInetHttp.Create;
end;

destructor TGxtSmsService.Destroy;
begin
  fHttpClient.Free;
  inherited;
end;

function TGxtSmsService.SendSms(const UserID, Phone: AnsiString; const Msg: WideString;
  out ErrCode: Integer; out ErrMsg: WideString): Boolean;
var
  url: AnsiString;
  response, status: AnsiString;
begin
  Result := False;
  url := Format(SmsServiceUrl, [SMSMD5(UserID + FormatDateTime('yyyy-m-d', Now)),
    UserID, Phone, URLEncode(Msg)]);
  try
    response := HttpGet(fHttpClient, url);
    if XMLGetInnerXMLA(response, 'status', status) and (status = '1') then
    begin
      ErrCode := 0;
      ErrMsg := '';
      Result := True;
    end
    else begin
      ErrCode := $7fffffff;
      ErrMsg := response;
    end;
  except
    on E: Exception do
    begin
      SendExceptionToDebugger('SendSms', E);
      ErrCode := $7fffffff;
      ErrMsg := E.Message;
    end;
  end;
end;

end.
